package com.airticketbooking.service.serviceImpl;

import com.airticketbooking.mapper.*;
import com.airticketbooking.po.Order;
import com.airticketbooking.po.OrderStatistics;
import com.airticketbooking.po.UserStatistics;
import com.airticketbooking.service.DataStatisticsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author Mr.J
 * @version 1.0.0
 * @Date 2024/12/21
 * @desc
 */
@Service
@Transactional
@RequiredArgsConstructor
public class DataStatisticsServiceImpl implements DataStatisticsService {

	private final OrderMapper orderMapper;

	private final OrderWithTicketMapper orderWithTicketMapper;

	private final FlightScheduleMapper flightScheduleMapper;

	private final UserMapper userMapper;

	private final MemberMapper memberMapper;


	@Override
	public OrderStatistics getOrderStatistics(Date startTime, Date endTime) {


		List<Order> orders = orderMapper.ordersWhichcompletedInRangeTime(startTime, endTime);

		if (orders.size() == 0) {
			throw new IllegalArgumentException("没有找到完成订单");
		}


		BigDecimal totalAmountDue = BigDecimal.ZERO;
		Integer totalCompletedOrders = 0;
		Integer totalCompletedTickets = 0;
		for (Order order : orders) {
			totalAmountDue = totalAmountDue.add(order.getActualAmountDue());

			List<Integer> ticketIdsByOrderId = orderWithTicketMapper.getTicketIdsByOrderId(order.getOrderId());

			totalCompletedTickets += ticketIdsByOrderId.size();

		}
		totalCompletedOrders = orders.size();

//		统计航班总数
		Integer totalFlights = flightScheduleMapper.countFlightsInRangeTime(startTime, endTime);

//		组装OrderStatistics对象
		OrderStatistics orderStatistics = new OrderStatistics();
		orderStatistics.setTotalEarnedAmount(totalAmountDue);
		orderStatistics.setTotalCompletedOrders(totalCompletedOrders);
		orderStatistics.setTotalCompletedTickets(totalCompletedTickets);
		orderStatistics.setTotalFlightSchedules(totalFlights);

		return orderStatistics;

	}

	@Override
	public UserStatistics getUserStatistics(Date startTime, Date endTime) {

//		统计用户总数

		Integer totalUsersNum = userMapper.getAllUsers();


//		统计新增用户数，inTimeRangeTime方法是自定义的sql方法，用于查询指定时间范围内的新增用户

		Integer totalNewUsersNum = userMapper.getUsersNumInRangeTime(startTime, endTime);


//		统计总会员数

		Integer totalMembersNum = memberMapper.getAllMembers();


//		统计新增会员数，inTimeRangeTime方法是自定义的sql方法，用于查询指定时间范围内的新增会员

//把startTime和endTime的Date拿出来

		Integer totalNewMembersNum = memberMapper.getMembersNumInRangeTime(startTime, endTime);


		UserStatistics userStatistics = new UserStatistics();
		userStatistics.setTotalUsers(totalUsersNum);
		userStatistics.setNewAddUsersInRangeTime(totalNewUsersNum);
		userStatistics.setTotalMembers(totalMembersNum);
		userStatistics.setNewAddMembersInRangeTime(totalNewMembersNum);


		return userStatistics;

	}
}
